<template>
  <page-container title="已结算订单" :showBack="true">
    <template v-slot:nav-left>
      <view class="nav-left" @click="goBack">
        <uni-icons type="left" size="20" color="#d4af37"></uni-icons>
      </view>
    </template>
    <view class="order-page">
      <!-- 顶部选项卡 -->
      <view class="tabs" v-if="false">
        <view class="tab" :class="{ active: currentTab === 0 }" @click="switchTab(0)">
          进行中
        </view>
        <view class="tab" :class="{ active: currentTab === 1 }" @click="switchTab(1)">
          已交付
        </view>
      </view>

      <!-- 筛选栏 -->
      <view class="filter-bar" v-if="false">
        <view class="filter-item">
          <text>产品：</text>
          <picker @change="onProductChange" :value="productIndex" :range="productOptions">
            <text>{{ productOptions[productIndex] }} ▼</text>
          </picker>
        </view>

        <view class="filter-item">
          <text>类型：</text>
          <picker @change="onTypeChange" :value="typeIndex" :range="typeOptions">
            <text>{{ typeOptions[typeIndex] }} ▼</text>
          </picker>
        </view>

        <view class="filter-item">
          <text>时间：</text>
          <picker @change="onTimeChange" :value="timeIndex" :range="timeOptions">
            <text>{{ timeOptions[timeIndex] }} ▼</text>
          </picker>
        </view>
      </view>
      <!-- 订单列表 -->
      <scroll-view class="order-list" scroll-y @scrolltolower="loadMore"
        :style="{ height: '100vh' }" :scroll-top="forceScrollTop">
        <view class="order-item" v-for="(item, index) in orderList" :key="item.id"
          @click="handleDetails(item)">
          <view class="order-content">
            <view class="order-header">
              <text class="order-no">订单号：{{ item.orderNo }}</text>
              <text class="order-status" :class="orderStatusStyle[item.orderStatus]">{{
                orderStatusOptions[item.orderStatus] }}</text>
            </view>
            <view class="order-info-warps">
              <view class="order-info">
                <text class="order-time">{{ item.orderTime }}</text>
              </view>
            </view>
            <view class="order-info-warps">
              <view class="order-info">
                <text class="order-no">物料：{{ materialTypeOptions[item.materialType] }}</text>
              </view>
              <view class="order-info">
                <text class="order-no">买/卖：{{ item.orderType === 'BUY' ? '买料' : '卖料' }}</text>
              </view>

            </view>
            <view class="order-info-warps">
              <view class="order-info">
                <text class="order-no">下单单价：{{ item.orderPrice || '--' }}</text>
              </view>
              <view class="order-info">
                <text class="order-no">重量（g）：{{ item.weight || '--' }}</text>
              </view>
            </view>
            <view class="order-info-warps">
              <view class="order-info">
                <text class="order-no">定金：{{ formatNumber(item.retainerAmount) || '--' }}</text>
              </view>
              <view class="order-info">
                <text class="order-no">仓管费：{{ item.manageFee || '--' }}</text>
              </view>
            </view>
            <view class="order-info-warps">
              <view class="order-info">
                <text class="order-no">结算单价：{{ item.settlePrice }}</text>
              </view>
              <view class="order-info">
                <text class="order-no">结算金额：{{ formatNumber(item.retainerAmountBalance) }}</text>
              </view>
            </view>
            <view class="order-info-warps">
              <view class="order-info">
                <text class="order-no">结算时间：{{ item.settleTime || '--' }}</text>
              </view>
            </view>
          </view>
        </view>

        <!-- 加载更多提示 -->
        <view class="load-more">
          <view v-if="loading" class="loading">
            <text class="loading-text">加载中...</text>
            <view class="loading-dots">
              <view class="dot"></view>
              <view class="dot"></view>
              <view class="dot"></view>
            </view>
          </view>
          <text v-else-if="noMore && orderList.length > 0" class="no-more">没有更多数据了</text>
          <text v-else-if="orderList.length === 0" class="empty">暂无订单数据</text>
        </view>
      </scroll-view>
    </view>
  </page-container>
</template>

<script>
import { isLoggedIn } from '@/utils/auth'
export default {
  data() {
    return {
      materialTypeOptions: {
        'GOLD': '黄金',
        'SILVER': '白银',
        'PLATINUM': '铂金',
        'PALLADIUM': '钯金',
      },
      orderStatusOptions: {
        'WAIT_PAY': '待支付',
        'PENDING': '已定价',
        'WAIT_SHIPMENT': '待发货',
        'COMPLETED': '已结算',
        'CANCELLED': '已结算',
        'PARTIALLY_FILLED': '部分成交',
        'FILLED': '已成交',
      },
      orderStatusStyle: {
        'WAIT_PAY': 'warning',
        'PENDING': 'warning',
        'WAIT_SHIPMENT': 'warning',
        'COMPLETED': 'success',
        'CANCELLED': 'success',
        'PARTIALLY_FILLED': 'warning',
        'FILLED': 'success',
      },
      currentTab: 0, // 当前选中的标签页 0-进行中 1-已交付

      // 筛选选项
      productIndex: 0,
      productOptions: ['全部', '黄金', '白银'],

      typeIndex: 0,
      typeOptions: ['全部', '卖料', '买料'],

      timeIndex: 0,
      timeOptions: ['全部', '近七天', '一个月', '半年'],

      // 订单数据
      orderList: [],
      page: 1,
      pageSize: 20,
      loading: false,
      noMore: false,
      refreshing: false, // 下拉刷新状态

      // 滚动区域高度
      scrollHeight: 0,
      // 添加强制滚动到顶部的标识
      forceScrollTop: 0,

      // 防抖定时器
      loadMoreTimer: null,
    }
  },
  onShow() {
    if (isLoggedIn()) {
      this.loadOrders();
    } else {
		uni.removeStorageSync("token");
		uni.removeStorageSync("customerInfo");
      uni.showToast({
        title: '请先登录',
        icon: 'none'
      });
    }
  },
  onLoad() { },

  onUnload() {
    // 清理定时器
    if (this.loadMoreTimer) {
      clearTimeout(this.loadMoreTimer);
      this.loadMoreTimer = null;
    }
  },
  methods: {
    goBack() {
      setTimeout(() => {
        uni.navigateBack()
      }, 100)
    },
    // 格式化数字，添加千分符
    formatNumber(num) {
      if (num === null || num === undefined || num === '') {
        return '--';
      }
      const number = parseFloat(num);
      if (isNaN(number)) {
        return '--';
      }
      return number.toLocaleString('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      });
    },

    // 切换标签页
    switchTab(index) {
      if (this.currentTab !== index) {
        this.currentTab = index;
        this.page = 1;
        this.noMore = false;
        this.orderList = [];
        this.loadOrders();
      }
    },

    // 加载订单数据
    async loadOrders() {
      if (this.loading || this.noMore) return;
      this.loading = true;
      try {
        let params = {
          "size": this.pageSize,
          "current": this.page,
          // "materialType": "string",
          // "orderType": "BUY",
          // "orderStatus": "WAIT_PAY",
          // "cusId": "string",
          // "minOrderTime": "string",
          // "maxOrderTime": "string"
        }
        let res = await this.$http.post('/applet/customer/orders/settleList', params)

        const newOrders = res.data.records || [];

        // 调试：检查是否有重复ID
        const newOrderIds = newOrders.map(order => order.id);
        const duplicateIds = newOrderIds.filter((id, index) => newOrderIds.indexOf(id) !== index);
        if (duplicateIds.length > 0) {
        }

        // 如果是第一页，直接替换数据
        if (this.page === 1) {
          this.orderList = newOrders;
        } else {
          // 如果不是第一页，累加数据并去重
          const existingIds = new Set(this.orderList.map(order => order.id));
          const uniqueNewOrders = newOrders.filter(order => !existingIds.has(order.id));
          this.orderList = [...this.orderList, ...uniqueNewOrders];
        }

        // 判断是否还有更多数据
        if (newOrders.length < this.pageSize) {
          this.noMore = true;
        }

        this.page++;
      } catch (error) {
        // console.error('加载订单失败:', error);
        uni.showToast({
          title: error.msg || '加载失败',
          icon: 'none'
        });

        // 如果是第一页加载失败，显示空状态
        if (this.page === 1) {
          this.orderList = [];
        }
      } finally {
        this.loading = false;
      }
    },

    // 触底加载更多
    loadMore() {
      // 清除之前的定时器
      if (this.loadMoreTimer) {
        clearTimeout(this.loadMoreTimer);
      }

      // 防抖处理，避免频繁触发
      this.loadMoreTimer = setTimeout(() => {
        if (!this.loading && !this.noMore) {
          this.loadOrders();
        }
      }, 100);
    },

    // 下拉刷新
    async onRefresh() {
      return;
      this.refreshing = true;
      this.page = 1; // 刷新时重置页码
      this.noMore = false;
      this.orderList = [];
      
      // 重置滚动位置到顶部
      this.scrollToTop();
      
      await this.loadOrders();
      
      // 刷新完成后，确保滚动到顶部
      this.$nextTick(() => {
        this.scrollToTop();
      });
      
      this.refreshing = false;
    },

    handleDetails(item) { },

    // 筛选条件变化
    onProductChange(e) {
      this.productIndex = e.detail.value;
      this.refreshList();
    },

    onTypeChange(e) {
      this.typeIndex = e.detail.value;
      this.refreshList();
    },

    onTimeChange(e) {
      this.timeIndex = e.detail.value;
      this.refreshList();
    },

    // 刷新列表
    refreshList() {
      this.page = 1;
      this.noMore = false;
      this.orderList = [];
      this.selectedOrders = [];
      this.isAllSelected = false;
      
      // 重置滚动位置到顶部
      this.scrollToTop();
      
      this.loadOrders();
      
      // 加载完成后确保滚动到顶部
      this.$nextTick(() => {
        this.scrollToTop();
      });
    },

    // 强制滚动到顶部
    scrollToTop() {
      this.forceScrollTop = 1;
      this.$nextTick(() => {
        this.forceScrollTop = 0;
      });
    }
  }
}
</script>
<style scoped lang="scss">
@import '@/uni.scss';

.order-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f5f5;
}

.tabs {
  display: flex;
  height: 80rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #eee;
}

.tab {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 28rpx;
  color: #666;
}

.tab.active {
  color: $uni-text-color-black;
  position: relative;
}

.tab.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 80rpx;
  height: 4rpx;
  background-color: $uni-text-color-black;
}

.filter-bar {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  padding: 30rpx 20rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #eee;
}

.select-all {
  display: flex;
  align-items: center;
  margin-right: 30rpx;
  font-size: 26rpx;
}

.filter-item {
  display: flex;
  align-items: center;
  margin-right: 20rpx;
  font-size: 26rpx;
  color: #666;
}

.order-list {
  flex: 1;
  overflow: hidden;
}

.order-item {
  display: flex;
  align-items: center;
  padding: 20rpx;
  margin: 20rpx;
  background-color: #fff;
  border-radius: 10rpx;
  box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
}

.order-content {
  flex: 1;
  margin-left: 20rpx;
}

.order-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10rpx;
}

.order-no {
  font-size: 26rpx;
  color: #333;
  margin-right: 20rpx;
}

.order-status {
  font-size: 24rpx;
}

.order-status.warning {
  color: #fff;
  background-color: #FF9500;
  padding: 4rpx 10rpx;
  border-radius: 10rpx;
}

.order-status.success {
  color: #fff;
  background-color: #4CD964;
  padding: 4rpx 10rpx;
  border-radius: 10rpx;
}

.order-status.error {
  color: #fff;
  background-color: #FF3B30;
  padding: 4rpx 10rpx;
  border-radius: 10rpx;
}

.order-info {
  display: flex;
  flex-direction: column;
  flex: 1;

}

.price-update-time {
  font-size: 20rpx;
  color: #999;
  margin-top: 4rpx;
}

.product-name {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 5rpx;
}

.order-time {
  font-size: 24rpx;
  color: #999;
}

.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.order-price {
  font-size: 28rpx;
  color: $uni-text-color-black;
  // font-weight: bold;
}

.order-price.updating {
  color: #FF9500;
  /* 价格更新时的颜色 */
  animation: pulse 1s infinite;
  /* 添加闪烁动画 */
}

.order-actions {
  display: flex;
  margin-top: 10rpx;
  // justify-content: flex-end;
}

.btn {

  padding: 0 20rpx;
  height: 50rpx;
  line-height: 50rpx;
  font-size: 24rpx;
  border-radius: 10rpx;
  background-color: #fff;
  color: $uni-text-color-orange;
  background-color: $uni-text-color-black;
  margin-right: 20rpx !important;
  margin-left: 0 !important;
}

.load-more {
  text-align: center;
  padding: 20rpx;
  font-size: 24rpx;
  color: #999;
}

.loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.loading-text {
  margin-bottom: 10rpx;
}

.loading-dots {
  display: flex;
  align-items: center;
  justify-content: center;
}

.dot {
  width: 8rpx;
  height: 8rpx;
  border-radius: 50%;
  background-color: #999;
  margin: 0 4rpx;
  animation: loading 1.4s infinite ease-in-out both;
}

.dot:nth-child(1) {
  animation-delay: -0.32s;
}

.dot:nth-child(2) {
  animation-delay: -0.16s;
}

@keyframes loading {

  0%,
  80%,
  100% {
    transform: scale(0);
    opacity: 0.5;
  }

  40% {
    transform: scale(1);
    opacity: 1;
  }
}

@keyframes pulse {
  0% {
    opacity: 1;
  }

  50% {
    opacity: 0.6;
  }

  100% {
    opacity: 1;
  }
}

.no-more {
  color: #999;
}

.empty {
  color: #ccc;
  font-size: 26rpx;
}

/* 定金操作弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: #fff;
  border-radius: 40rpx;
  width: 90%;
  position: relative;
  margin: 0 56rpx;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
  padding: 30rpx 20rpx;
  border-bottom: 2rpx solid #eee;
}

.modal-title {
  font-size: 33rpx;
  font-weight: bold;
  color: $uni-text-color-black;
}

.modal-close {
  font-size: 40rpx;
  color: #999;
  font-weight: bold;
}

.modal-body {
  padding-bottom: 20rpx;
  padding-left: 20rpx;
  padding-right: 20rpx;
}

.form-item {
  flex: 1;
  display: flex;
  align-items: center;
  margin-bottom: 26rpx;
  font-size: 28rpx;
  color: #333;
}

.form-label {
  font-weight: bold;
  margin-right: 20rpx;
  width: 150rpx;
  text-align: right;
}

.form-value {
  font-size: 28rpx;
  color: $uni-text-color-black;
  font-weight: bold;
}

.form-input {
  flex: 1;
  font-size: 28rpx;
  color: $uni-text-color-black;
  padding: 20rpx 15rpx;
  border: 1rpx solid #eee;
  border-radius: 8rpx;
  background-color: #f9f9f9;
  min-width: 200rpx;
  transition: all 0.3s ease;
}

.form-input:focus {
  border-color: $uni-text-color-orange;
  background-color: #fff;
  box-shadow: 0 0 0 2rpx rgba(255, 149, 0, 0.2);
}

.modal-footer {
  display: flex;
  justify-content: space-around;
  padding: 30rpx 26rpx;
  border-top: 2rpx solid #eee;
}

.btn-cancel,
.btn-confirm {
  flex: 1;
  margin: 0 10rpx;
  padding: 8rpx 0;
  font-size: 28rpx;
  border-radius: 16rpx;
  border: 2rpx solid transparent;
  color: #fff;
  font-weight: bold;
}

.btn-cancel {
  background-color: transparent;
  color: $uni-text-color-black;
  border: 2rpx solid $uni-text-color-black;
}

.btn-confirm {
  color: $uni-text-color-orange;
  background-color: $uni-text-color-black;
}

.btn-confirm:disabled {
  background-color: #ccc;
  color: #666;
}

/* 弹窗动画效果 */
.modal-overlay {
  animation: fadeIn 0.3s ease;
}

.modal-content {
  animation: slideIn 0.3s ease;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }

  to {
    opacity: 1;
  }
}

@keyframes slideIn {
  from {
    transform: translateY(-50rpx);
    opacity: 0;
  }

  to {
    transform: translateY(0);
    opacity: 1;
  }
}

/* 响应式设计 */
@media screen and (max-width: 750rpx) {
  .modal-content {
    width: 90%;
  }



  .form-input {
    margin-top: 10rpx;
    width: calc(100% - 40rpx);
  }
}

.order-info-warps {
  display: flex;
  gap: 10rpx;
  align-items: center;
  margin-bottom: 20rpx;
}
</style>